package com.itheima.goods.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.goods.entity.GoodsEntity;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangyan
 * @date 2021/3/24 17:43
 */
@CanalEventListener //声明为canal的监听类
public class GoodsListener {

    @Autowired
    private RedisTemplate redisTemplate;

    //设置监听哪个数据库,哪张表
    @ListenPoint(schema = "redis", table = "tb_goods")
    /**
     * @param CanalEntry.EventType 监听到的事件(CRUD)
     * @param CanalEntry.RowData  监听到的增量数据
     */
    public void updateRedisGoodsInfo(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {

        //获取改变之前的数据
        rowData.getBeforeColumnsList().forEach((c) -> System.out.println("改变前的数据:" + c.getName() + "::" + c.getValue()));

        //获取改变之后的数据
        rowData.getAfterColumnsList().forEach((c) -> System.out.println("改变之后的数据:" + c.getName() + "::" + c.getValue()));

        //todo 更新数据到redis
        //map接收数据
        Map map = new HashMap<>();
        //遍历获取
        rowData.getAfterColumnsList().forEach((c) -> map.put(c.getName(), c.getValue()));

        //转Json字符串
        String jsonString = JSON.toJSONString(map);
        //Json字符串转实体类
        GoodsEntity goodsEntity = JSON.parseObject(jsonString, GoodsEntity.class);
        System.out.println(goodsEntity);

        //更新缓存
        redisTemplate.opsForValue().set("goodsId:" + goodsEntity.getId(), goodsEntity, 30, TimeUnit.MINUTES);
    }
}
